<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/8/4
 * Time: 13:40
 */

namespace app\api\controller;

use app\service\MemberService;
use app\service\OrderService;
use \Factory;
use phpmailer\BaseException;
use Protocol\Curl;
use think\Db;

/**
 * 订单
 * @author   juzi
 * @blog    https://blog.csdn.net/juziaixiao
 * @version  0.0.1
 * @datetime 2020年8月4日13:41:15
 */
class Order  extends Common
{
    /**
     * [__construct 构造方法]
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年8月4日13:41:15
     */
    public function __construct()
    {
        // 调用父类前置方法
        parent::__construct();


    }


    /**
     * [SaveInfo 修改订单 ]
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年8月4日13:41:15
     */
    public function SaveInfo()
    {

        $this->isLogin();
        // 开始操作
        $params = $this->data_post;

        $data['where']=['id'=>$params['order_id']];
        $data['update']=['send_notice'=>$params['send_notice']];
        $data['table']='member_orderdetail';
        $data['msg']='修改订单详情失败';
        $data['errorCode']='4003';
        OrderService::SaveOrder($data);

        return json(DataReturn('保存成功', 0));
    }

    /**
     * [OrderDetail 订单详情]
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年8月4日13:41:15
     */
    public function OrderDetail()
    {
        $this->isLogin();
        $params = $this->data_get;

        $field='mo.id mo_id,mo.receive_phone,mo.receive_name,
        mo.member_id,mo.province,mo.city,mo.area,mo.address,
        mo.pay_price,mo.cheap_price,mo.total_price,mo.pay_type,
        mo.pay_time,mo.order_number,mo.member_code';
        // 获取列表
        $data_params = [
            'm' => 0,
            'n' => 1,
            'page' => false,
            'where' => ['mo.id' => intval($params['order_id'])],
            'field'=>$field,
        ];
        // 查询用户状态是否正常
        MemberService::MemberStatusCheck('id', $this->member_id);
        $ret=OrderService::OrderList($data_params);
        $data = empty($ret['data'][0]) ? [] : $ret['data'][0];
        return DataReturn(true, 0,$data);

    }

    /**
     * [ExpressDetail 查看物流]
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年8月4日13:41:15
     */
    public function ExpressDetail(){
        $this->isLogin();
        $odetail_id = input("post.odetail_id");
        if(!empty($odetail_id))
            $_where = "e.status = 1 and mod.id =$odetail_id";
        $field = 'e.title,e.phone,e.status,mo.order_number,if(e.feetype =1,"已付","未付") feetype,e.address';
        $data_params = [
            'page' => false,
            'where' => $_where,
            'field'=>$field,
            'mine'=>'express', //物流
        ];
        $ret=OrderService::OrderList($data_params);
        $data = empty($ret['data'][0]) ? [] : $ret['data'][0];
        return json(apiDataReturn(true, '',$data));

    }


    /**
     * [SaveMo 取消订单]
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年8月4日13:41:15
     */

    public function CancelMo()
    {    $this->isLogin();
        $params = $this->data_post;
        $params['member_id']=$this->member_id;
        OrderService::SaveSerInfo($params);
        return json(DataReturn('取消成功',0));

    }

    #前端接口
    /**
     * [getCheckOrder 立即下单 ]
     * @Content 点击立即购买 和 购物车下单时
     * @param  array()
     */
    function getCheckOrder(){
        #购物传id  商品下订单 传数组
        #接受参数

        $info = $this->data_post;
        #购物车id
        $shopcarId =  input("post.shopcarId") ;
        if(!empty($shopcarId))
        {
            $memberId=$this->member_id;
        }else{
            $token=$info['token'];
            $memberId=cache($token)['id'];

        }
        if(!isset($memberId))
        {
            throw new BaseException(['code'=>403 ,'errorCode'=>1015,'msg'=>'请授权登录','status'=>false,'debug'=>false ]);

        }

        unset($info['token']);
        #处理数据
        $orderId = OrderService::getCheckOrder($info,$shopcarId, $memberId);

        if(!empty($orderId)){
            return array("status"=>true,"orderId"=>$orderId,'msg'=>'下单成功');

        }else{
            return array("status"=>false,"msg"=>"下单失败");

        }
    }
    /**
     * [getConfirm  确认订单页]
     * @Content 确认订单页
     * @param  null
     */
    public function getConfirm()
    {
        $this->isLogin();
        #查询订单确认 获取参数 订单id
        $params = input();
        $info = Db::table("member_order mo")
            ->field("mo.id order_id,mo.total_price,mod.id orderdetail_id ,mod.bizpro_name,mod.bizpro_imgurl,mod.bizpro_number,mod.bizpro_lable,mod.buy_num,mod.price,mod.bizpro_spec_value")
            ->join("member_orderdetail mod",'mod.order_id = mo.id')
            ->where(array("mo.id"=>$params['order_id']))
            ->select();
        foreach ($info as &$bv)
        {
            $re= json_decode($bv['bizpro_spec_value'],true);

            $bv['bizpro_spec_value'] =!empty($re) ? implode(",",$re) : '';
            $bv['bizpro_spec_value']=substr($bv['bizpro_spec_value'],-1)==','?substr($bv['bizpro_spec_value'],0,-2):$bv['bizpro_spec_value'];

            $bv['bizpro_lable']=explode(",",$bv['bizpro_lable']);
        }
        $data = array();
        $time = date("Y-m-d H:i:s");
        #查询是否有满减 开始时间<=当前的时间 <= 结束时间
        $reduction = Db::table("reduction")->where("'$time'>= start_time and '$time'<= end_time")->find();
        if(!empty($reduction)){
            $data['reduction_momey']=getPriceInfo($reduction['money']);
            $data['reduction_price']=getPriceInfo($reduction['price']);
        }
        $data['info']=$info;
        $data['mail']="快递包邮";
        $data['mo_id']=$params['order_id'];
        $data['order_number']=Db::name('member_order')->where('id='.$params['order_id'])->value('order_number');
        $data['total_price']=Db::name('member_order')->where('id='.$params['order_id'])->value('total_price');
        $data['count_num']=count($info);

        if(!empty($info))
        {
            return json(apiDataReturn(true, '',$data));

        }
    }
    /**
     * @param array
     * @content 订单确认页修改数量
     */
    function orderWriteNum(){
        $this->isLogin();
        $odetail_id = input("post.odetail_id");  //订单详情id
        $order_id = input("post.order_id");     //订单id
        $num = input("post.num");  //改完之后的数量
        $type = input("post.type");//1 加 2 减
        if(!empty($odetail_id) and !empty($order_id)){
            $orderinfo = Db::table("member_orderdetail")->field("price,order_id,buy_num")->where("id={$odetail_id}")->find();
            if($type == 1){
                #加
                $wnum = intval($num) - intval($orderinfo['buy_num']);
                $incprice =floatval($orderinfo['price']) * $wnum;
                #修改订单详情数量
                Db::table('member_orderdetail')->where(array('id'=>$odetail_id))->update(array('buy_num'=>$num));
                #增加订单总金额
                $res = Db::table('member_order')->where(array('id'=>$order_id))->setInc('total_price',$incprice);

            }else{
                #减
                $wnum = intval($num) - intval($orderinfo['buy_num']);
                $decprice =floatval($orderinfo['price']) * abs($wnum);
                #修改订单详情数量
                Db::table('member_orderdetail')->where(array('id'=>$odetail_id))->update(array('buy_num'=>abs($num)));
                #增加订单总金额
                $res = Db::table('member_order')->where(array('id'=>$order_id))->setDec('total_price',$decprice);
            }
            if($res){

                return json(apiDataReturn(true));
            }else{
                return json(apiDataReturn(false, '订单数量修改失败,请重试!'));

            }
        }else{
            return json(apiDataReturn(false, '订单详情id和订单id为空'));
        }
    }
    /**
     * @param array
     * @content 订单确认页点击 确认支付
     */
    function getConfirmPay(){
        $this->isLogin();
        $params = input();
        //$params['member_code']=strtoupper($params['member_code']);
        $params['phone']=$params['receive_phone'];
//        return json(apiDataReturn(true,'',$params));
        #调云盟时代的后台接口
        $Curl= new Curl();
        $memberCode = $Curl->post("https://meng.childpi.com/alliance/Api/getMemberCode",$params,'json');
//        $memberCode = $Curl->post("https://www.8a1.top/alliance/Api/getMemberCode",$params,'json');




        $false_status=false;
        if(json_decode($memberCode,true)['status'] == true){

            $false_status=true;
        }


        $res = Db::table("member_order")->where("id = '".$params['order_id']."'")
            ->update(array(
                'receive_name'=>$params['receive_name'],
                'receive_phone'=>$params['phone'],
                'member_code'=>$params['member_code'],
                'province'=>$params['province'],
                'city'=>$params['city'],
                'area'=>$params['area'],
                'address'=>$params['address'],
                'cheap_price'=>$params['cheap_price'],

            ));
        return json(apiDataReturn(true,'',['params'=>$params,'false_status'=>$false_status]));

    }
    /*
      * @context 微信支付 支付宝支付
      * */
    function ordersPay()
    {
        $this->isLogin();
        #支付类型 1 微信支付  2 支付宝支付
        $type = input("post.pay_type");
        $order_number = input("post.order_number");
        $price = input("post.price");
        //查询商品名称
        $order = Db::table('member_order mo')
            ->field('b.name,b.id')
            ->join("member_orderdetail mod",'mod.order_id = mo.id')
            ->join("bizpro b",'mod.bizpro_id = b.id')
            ->where("mo.order_number = $order_number")
            ->select();
        if(!empty($order))
            if(count($order)>1){
                $body= $order[0]['name'].'等多种商品';

            }else{
                $body= $order[0]['name'];
            }

        if($type == 1){
//            $openid = input("post.openid");
            $WxpayService = new WxpayService();
            $res = $WxpayService->JsApiPay($body, $order_number, $price);


            if ($res['return_code'] == true) {
                # 统一下单成功
                $orderstatus = Db::table("orderspay")->where(array("order_number" => $order_number))->select();
                if (empty($orderstatus)) {
                    Db::table("orderspay")->data(array("order_number" => $order_number, "sign" => $res['return_param']["sign"]))->insert();
                } else {
                    Db::table("orderspay")->where(array("order_number" => $order_number))->update(array("status" => 0));
                }
                return DataReturn('ok',0,$res['data']);
            } else {
                # 统一下单失败
                return DataReturn('no',-1);

            }
        }
        if($type == 2){

            #支付宝支付
            $AlipayService = new AlipayService();
            $res = $AlipayService->JsAliPay($body, $order_number, $price);
            $info = explode('&',urldecode($res));
            $re=[];
            foreach($info as $k=>$v){
                $re[explode('=',$v)[0]]=explode('=',$v)[1];

            }
            $result = json_decode($re['biz_content'],true);

            if (!empty($result['out_trade_no'])) {
                # 统一下单成功
                $orderstatus = Db::table("orderspay")->where(array("order_number" => $order_number))->select();
                if (empty($orderstatus)) {
                    Db::table("orderspay")->data(array("order_number" => $order_number,"sign" => $re['sign']))->insert();
                } else {
                    Db::table("orderspay")->where(array("order_number" => $order_number))->update(array("status" => 0));
                }

                return DataReturn('ok',0,$res);


            } else {
                # 统一下单失败
                return DataReturn('no',-1);
            }
        }

    }



}